package com.cory.admin.sys.core.privilege.tag;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import com.cory.admin.sys.config.AdminConstants;
import com.cory.boot.config.FreemarkerConfig.FreemarketTag;
import com.cory.boot.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Component
@FreemarketTag(name = "hasAnyPermission", prefix="privilege")
public class HasAnyPermissionTag implements TemplateDirectiveModel {

    /**
     * "权限"参数名称
     */
    private static final String PARAM_NAME = "permissions";

    @Autowired
    private HttpServletRequest request;

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void execute(Environment env, Map params, TemplateModel[] templateModels, TemplateDirectiveBody body) throws TemplateException, IOException {
        List<String> permissions = FreeMarkerUtils.getParameter(PARAM_NAME, List.class, params);
        
        boolean hasPermission;
        List<String> userPermissions = (List<String>)request.getSession().getAttribute(AdminConstants.SESSION_USER_PERMISSION);
        if (CollectionUtils.isEmpty(permissions) || CollectionUtils.isEmpty(userPermissions)) {
            hasPermission = false;
        } else {
            hasPermission = permissions.stream().anyMatch(userPermissions::contains);
        }
        
        if (hasPermission && body != null)
            body.render(env.getOut());
    }
}